<template>
    <common-modal
        ref="modalRef"
        v-bind="attrs"
        @sure="search"
        @cancel="handleCancel"
        @before-close="reset"
        @open="handleOpen"
    >
        <el-form
            label-width="130px"
            :rules="rules"
            ref="formRef"
            :inline="false"
            :model="formData"
        >
            <el-form-item label="平台名称：" prop="platformName">
                <el-input
                    v-model="formData.platformName"
                    placeholder="请输入平台名称"
                    clearable
                />
            </el-form-item>
            <el-form-item label="标识：" prop="platformLogo">
                <el-input
                    v-model="formData.platformLogo"
                    placeholder="请输入标识"
                    clearable
                />
            </el-form-item>
            <el-form-item label="分成比例设置：" prop="platformRateList">
                <rate-set
                    ref="rateRef"
                    v-model:list="formData.platformRateList"
                />
            </el-form-item>
            <el-form-item label="管理后台：" prop="manageUrl">
                <el-input
                    v-model="formData.manageUrl"
                    placeholder="请输入管理后台"
                    clearable
                />
            </el-form-item>
            <el-form-item label="投手账户分配：" prop="platformAccountList">
                <account-set
                    ref="accountRef"
                    :pitcherList="formList.pitcherList"
                    v-model:list="formData.platformAccountList"
                />
            </el-form-item>
            <el-form-item label="状态：" prop="state">
                <el-radio-group v-model="formData.state">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">正常</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
    </common-modal>
</template>
<script>
export default {
    inheritAttrs: false,
};
</script>
<script setup>
import { reactive, useAttrs, ref, onMounted } from "vue";
import commonModal from "@/components/commonModal.vue";
import RateSet from './rateSet.vue'
import AccountSet from './accountSet.vue'
import useForm from "@/hooks/useForm";
import { ElMessage } from "element-plus";
import { GetPitcher } from '@/apis/user'
import { GetPlatformById, AddPlatform, EditPlatform } from '@/apis/platform'
const props = defineProps({
    type: {
        type: String,
        default: "add",
    },
    curForm: {
        type: [Object, String],
        default: () => ({}),
    },
});
const attrs = useAttrs();
const formData = reactive({
    platformName: "",
    platformLogo: "",
    manageUrl: "",
    state: 1,
    platformAccountList: [],
    platformRateList: []
});
const modalRef = ref(null);
// 确定
const handleSure = async () => {
    const optionApi = props.curForm.id ? EditPlatform : AddPlatform
    await optionApi(formateSaveData());
    ElMessage.success({
        message: "操作成功",
        type: "success",
    });
    emits("success");
    handleCancel();
};
// 格式化提交数据
const formateSaveData = () => {
    let { platformAccountList, platformRateList } = formData
    return {
        ...formData,
        platformAccountList: (platformAccountList || []).map(v => {
            return {
                ...v,
                platformId: props.curForm && props.curForm.id || ''
            }
        }),
        platformRateList: (platformRateList || []).map(v => {
            return {
                ...v,
                platformId: props.curForm && props.curForm.id || '',
                beginTime: v.times[0],
                endTime: v.times[1],
                rate: (v.rate / 100).toFixed(2)
            }
        }),
    }
}
const rateRef = ref(null)
const validateRate = (rule, value, cb) => {
    rateRef.value?.validate().then(res => {
        cb()
    }).catch(err => cb(new Error(err)))
}
const accountRef = ref(null)
const { formRef, search, reset } = useForm(handleSure);
const validateAccount = (rule, value, cb) => {
    accountRef.value?.validate().then(res => {
        cb()
    }).catch(err => cb(new Error(err)))
}
const rules = {
    platformName: [{ required: true, message: "请输入平台名称" }],
    platformLogo: [{ required: true, message: "请输入平台标识" }],
    state: [{ required: true, message: "请选择状态" }],
    platformAccountList: [{ validator: validateAccount, message: "请输入完善投手账户分" }],
    platformRateList: [{ validator: validateRate, message: "请输入完善分成比例设置" }],
};

// 取消 关闭弹窗
const handleCancel = () => {
    modalRef.value?.close();
};

// 确定
const emits = defineEmits(["success"]);

// 打开弹窗
const handleOpen = () => {
    const { type, curForm } = props;
    if (!curForm || !curForm.id) return 
    GetPlatformById(curForm.id).then(res => {
        console.log('res: ', res);
        Object.assign(formData, { 
            ...res,
            platformRateList: (res.platformRateList || []).map(v => {
                return {
                    ...v,
                    times: [v.beginTime, v.endTime],
                    rate: v.rate * 100
                }
            })
        })
    })
};
const formList = reactive({
    pitcherList: [], // 投手列表
})
onMounted(() => {
    // 获取投手列表
    GetPitcher().then(res => {
        formList.pitcherList = res
    })
})
</script>
